/**
 * 基础服务抽象类
 * 职责：
 * 1. 定义Service层统一接口
 * 2. 提供生命周期管理
 * 3. 统一日志记录
 * 4. 依赖注入支持
 */
export abstract class BaseService {
    protected readonly serviceName: string;
    protected isInitialized: boolean = false;

    constructor() {
        this.serviceName = this.constructor.name;
    }

    /**
     * 服务初始化
     * 子类可重写此方法进行特定初始化
     */
    async init(): Promise<void> {
        if (this.isInitialized) {
            console.warn(`Service ${this.serviceName} already initialized`);
            return;
        }
        
        console.log(`Initializing service: ${this.serviceName}`);
        await this.onInit();
        this.isInitialized = true;
        console.log(`Service ${this.serviceName} initialized successfully`);
    }

    /**
     * 服务销毁
     * 子类可重写此方法进行资源清理
     */
    async destroy(): Promise<void> {
        if (!this.isInitialized) {
            console.warn(`Service ${this.serviceName} not initialized`);
            return;
        }
        
        console.log(`Destroying service: ${this.serviceName}`);
        await this.onDestroy();
        this.isInitialized = false;
        console.log(`Service ${this.serviceName} destroyed successfully`);
    }

    /**
     * 检查服务是否已初始化
     */
    protected ensureInitialized(): void {
        if (!this.isInitialized) {
            throw new Error(`Service ${this.serviceName} not initialized. Call init() first.`);
        }
    }

    /**
     * 子类重写此方法实现特定初始化逻辑
     */
    protected async onInit(): Promise<void> {
        // 默认空实现
    }

    /**
     * 子类重写此方法实现特定销毁逻辑
     */
    protected async onDestroy(): Promise<void> {
        // 默认空实现
    }

    /**
     * 获取服务名称
     */
    getServiceName(): string {
        return this.serviceName;
    }

    /**
     * 检查服务状态
     */
    isReady(): boolean {
        return this.isInitialized;
    }

    /**
     * 日志记录方法
     */
    protected log(message: string, level: 'info' | 'warn' | 'error' = 'info'): void {
        const timestamp = new Date().toISOString();
        const logMessage = `[${timestamp}] [${this.serviceName}] ${message}`;
        
        switch (level) {
            case 'info':
                console.log(logMessage);
                break;
            case 'warn':
                console.warn(logMessage);
                break;
            case 'error':
                console.error(logMessage);
                break;
        }
    }
}
